// pages/package/nav_supply_approve/supply_approve.js
const mybehavior = require("../../../../../../behaviors/requests")
import Dialog from '@vant/weapp/dialog/dialog';
Page({
  /**
   * 页面的初始数据
   */
  behaviors: [mybehavior],
  data: {
    page_size: 1,
    page: 1,
    total: 0,
    page_all: 0,
    handling_show: true,
    handling_num: 7,
    baseUrl: "https://logisticsengineering.gree.com/package_integrated_api/container_outdoor_manage",
    now_Url: "",
    phone_num: "",
    title_val: "签审完结",
    activeName: [],
    status: 0,

    popup_show: false,
    list: [],
    sp_show: false,
    key: "",
    reason: "ok",
    action: "agree",
    qsyj_options: ["agree", "disagree"],
    agree_btn: "danger",
    disagree_btn: "default",
    caozuo_show: false,
    caozuo_word: "审批",
    bh_show: false,
    bh_reason: "",
    row_data: "",
    hsbzqd_show: false,
    spjl_show: false,
    hsbzqd_list: [],
    spjl_list: [],
    photo_list: [],
    previewImageClick: false,


    xuhua_style: "background-color:rgba(255,255,255,0.9)",
    id_shuiyin: "",
    spjl_list_1: [],
    splj_index: 1,
    splj_total: 0,
    task_row_data: {},
    activeNamesDetail: ['1'],
    onActiveChangeStep: [],
    task_id: "",
    inspect_show: true,
    data_arr: {},
    pack_total: 0,
    pack_index: 1,
    pack_list_1: [],
    steps_img: false,
    img_src:''


  },

  // 显示当前处理人信息
  showHandlePerson(e) {
    console.log(e.currentTarget.dataset.row_data);
    let msg = e.currentTarget.dataset.row_data
    Dialog.alert({
      title: msg,
    }).then(() => {
      // on close
    });
  },
  // shoRes 
  showRes(e) {
    console.log(e.currentTarget.dataset.row_data);
    let msg = e.currentTarget.dataset.row_data
    Dialog.alert({
      title: msg,
    }).then(() => {
      // on close
    });
  },
  onActiveDetailChange(event) {
    this.setData({
      activeNamesDetail: event.detail,
    });
  },
  onActiveChangeStep(event) {
    this.setData({
      activeNamesStep: event.detail,
    });
  },
  previewPhoto2(e) {
    let img_url = "https://logisticsengineering.gree.com/package_integrated_api/photo_manage/fs_download?file_id=" + e.currentTarget.dataset.row_data
    console.log(img_url);
    let u = this.data.list[0].vehicle_images1
    console.log("1", u);
    wx.previewImage({
      current: img_url,
      urls: u,
    })
  },
  // 获取账户信息
  getSelfData() {
    let self = this
    var url = "https://logisticsengineering.gree.com/package_integrated_api/user_manage/get_self_r"
    var data = {}
    var token = wx.getStorageSync('token');
    wx.request({
      url,
      data,
      header: {
        "Authorization": token
      },
      dataType: "json",
      method: "POST",
      success(response) {
        const res = response.data;
        if (res.code == 20000) {
          const result = res;
          wx.setStorageSync('_id', result.data._id)

        }
      },
      fail(res) {
        console.log(res);
      }
    });
  },
  // 判断是否带id
  checkID() {
    let id = wx.getStorageSync("_id")
    if (!id) {
      this.getSelfData()
    }
    setTimeout(() => {
      this.getShuiyin()
    }, 1000)
  },

  // 获取水印
  getShuiyin() {
    let id = wx.getStorageSync("_id")
    let val = "background: url(https://logisticsengineering.gree.com/water_img/" + id + ".png);background-repeat: no-repeat;background-size:cover;"
    // console.log(val);
    this.setData({
      id_shuiyin: val
    })

    // https://logisticsengineering.gree.com/water_img/######_id#######.png

  },
  onAgree() {
    this.setData({
      agree_btn: "danger",
      reason: "ok",
      action: "agree",
      disagree_btn: "default",
    })
  },
  onDisgree() {
    this.setData({
      agree_btn: "default",
      action: "disagree",
      reason: "",
      disagree_btn: "danger",
    })
  },
  // 驳回弹框
  onBhShow() {
    var bh_arr = this.data.row_data.records
    var bh_val = bh_arr[bh_arr.length - 1].reason
    console.log(bh_val)
    this.setData({
      bh_show: true,
      bh_reason: bh_val
    });
  },
  // 驳回弹框确认
  onCzConfirm() {
    this.setData({
      bh_show: false,
    });
  },
  // 驳回弹框关闭
  onCzClose() {
    this.setData({
      bh_show: false,
    });
  },
  // 操作弹框确认
  onCzConfirm() {
    this.setData({
      caozuo_show: false,
    });
  },
  // 操作弹框关闭
  onCzClose() {
    this.setData({
      caozuo_show: false,
    });
  },




  try_upload() {
    let url = "https://logisticsengineering.gree.com/package_integrated_api/photo_manage"
    wx.navigateTo({
      url: '/pages/watermark_img_tool/img',
      success(res) {
        res.eventChannel.emit('acceptDataFromOpenerPage', url)

      }
    })
  },
  // 审批弹框确定按钮
  onSpConfirm() {
    if (this.data.reason == "" || this.data.action == "") {
      wx.showToast({
        title: '不能为空',
        icon: "error"
      })
    } else {
      wx.requestSubscribeMessage({
        tmplIds: ['Qq4EMCt24ZVzeR74sHCcdCgZyo7pus8Bf9knNoUHPpM'],

      })
      var url = this.data.baseUrl + "/inspect_container_outdoor"
      var data = {
        key: this.data.task_row_data.task._id,

        reason: this.data.img_src + '##' + this.data.reason,
        // reason: this.data.reason,
        action: this.data.action
      }
      console.log(data);
      this.post(url, data).then(res => {
        console.log("审批返回结果", res)
        if (res.code == 20000) {
          wx.showToast({
            title: res.msg,
            icon: "success"
          });
          setTimeout(function () {
            wx.reLaunch({
              url: '/packageB/pages/package/task_manager/task_manager',
            })
          }, 2000)
        } else {
          wx.showToast({
            title: res.msg,
            icon: "error"
          })
        }
      }).catch(err => {
        wx.showToast({
          title: err.msg,
          icon: 'error'
        })
      })

    }

  },
  // 审批弹框关闭
  onSpClose() {
    this.setData({
      sp_show: false,
      key: "",
      reason: "ok",
      action: "agree",
      agree_btn: "danger",
      disagree_btn: "default",
    });
  },
  // 点击审批按钮
  onApprove(e) {
    console.log(e.target.dataset.row_data);
    var row = e.target.dataset.row_data
    if (this.data.handling_show == true) {
      this.setData({
        key: row._id,
        row_data: row,
        sp_show: true,
      })
    } else {
      this.setData({
        key: row._id,
        row_data: row,
        caozuo_show: true,
      })
    }

  },
  // if (row.next_process === "编制") {
  //   this.setData({
  //     key: row._id,
  //     row_data: row,
  //     caozuo_show: true,
  //   })
  // } else {
  //   this.setData({
  //     key: row._id,
  //     row_data: row,
  //     sp_show: true,
  //   })

  // }





  onChange(event) {
    this.setData({
      activeName: event.detail,
    });
  },
  pageUp() {
    var now_page = this.data.page
    if (now_page != 1) {
      now_page = now_page - 1
      this.setData({
        page: now_page
      })
      this.Submit()
    }


  },
  pageDown() {
    var now_page = this.data.page
    if (now_page < this.data.page_all) {
      now_page = now_page + 1
      this.setData({
        page: now_page
      })
      this.Submit()
    }

  },
  // 查询供应商用户注册申请列表
  getSupplyDatas(val) {

    var show_list = []
    show_list.push(val)
    for (var i in show_list) {
      show_list[i].outdoor_date = this.GMTToStr(show_list[i].outdoor_date).slice(0, 10)
      if (show_list[i].status == "done") {
        show_list[i].status1 = "审批通过"
      } else if (show_list[i].status == "pre") {
        show_list[i].status1 = "待审批"
      } else if (show_list[i].status == "inspect") {
        show_list[i].status1 = "审批中"
      } else {
        show_list[i].status1 = "被驳回"
      }
      if (show_list[i].safety_action == "agree") {
        show_list[i].safety_action1 = "正常出门"
      } else if (show_list[i].safety_action == "disagree") {
        show_list[i].safety_action1 = "异常出门"
      } else {
        show_list[i].safety_action1 = "待出门"
      }
      if (show_list[i].inspect_status[0].next_involved.length != 0) {
        var h_list = show_list[i].inspect_status[0].next_involved
        var handle_person = show_list[i].inspect_status[0].recycle_type + '-->'
        for (var j in h_list) {
          handle_person += '|' + h_list[j].name + '|'
        }
        show_list[i].handle_person = handle_person
      } else {
        show_list[i].handle_person = []
      }
      for (let i in show_list) {
        show_list[i].vehicle_images1 = show_list[i].vehicle_images
        for (let j in show_list[i].vehicle_images1) {
          show_list[i].vehicle_images1[j] = "https://logisticsengineering.gree.com/package_integrated_api/photo_manage/fs_download?file_id=" + show_list[i].vehicle_images1[j]
        }
      }
    }
    this.setData({
      list: show_list,
      previewImageClick: true,
    })


  },
  // 删除按钮
  onDelete() {
    var url = this.data.baseUrl + "/delete_container_outdoor"
    var data = {
      key: this.data.task_row_data.task._id,

    }
    console.log(data);
    this.post(url, data).then(res => {
      console.log("删除返回结果", res)
      if (res.code == 20000) {
        this.setData({
          caozuo_show: false,
        });
        wx.showToast({
          title: res.msg,
          icon: "success"
        });
        this.Submit()
      } else {
        wx.showToast({
          title: res.msg,
          icon: "error"
        })
      }
    }).catch(err => {
      wx.showToast({
        title: err.msg,
        icon: 'none'
      })
    })
  },
  // 预览照片
  previewPhoto(e) {
    let img_url = e.currentTarget.dataset.row_data
    let a = img_url.split('=')[1]
    let p_list = this.data.photo_list
    let u = []
    let us = []
    for (let i in p_list) {
      for (let j in p_list[i]) {
        if (p_list[i][j] == a) {
          u = p_list[i]
          for (let k in u) {
            us.push("https://logisticsengineering.gree.com/package_integrated_api/photo_manage/" + "fs_download?file_id=" + u[k])
          }
          // console.log("img", us);
        }
      }
    }
    wx.previewImage({
      current: img_url,
      urls: us,
    })
  },
  // 回收包装清单显示
  onOutdoorContainers(e) {
    console.log(e.target.dataset.row_data);
    var data_list = e.target.dataset.row_data
    let p_l = []
    var img_list = []
    for (var i in data_list) {
      img_list = data_list[i].container_photos
      p_l.push(data_list[i].container_photos)
      var img_show_list = []
      for (var j in img_list) {
        img_show_list.push("https://logisticsengineering.gree.com/package_integrated_api/photo_manage/" + "fs_download?file_id=" + img_list[j])
      }

      data_list[i].i_l = img_show_list
    }
    // console.log("1", img_show_list)
    let total = data_list.length
    let current_data = []
    current_data.push(data_list[0])
    this.setData({
      hsbzqd_show: true,
      hsbzqd_list: data_list,
      pack_total: total,
      photo_list: p_l,
      pack_list_1: current_data,
    });
  },
  onhsbzqdClose() {
    this.setData({
      hsbzqd_show: false
    })
  },
  onhsbzqdConfirm() {
    this.setData({
      hsbzqd_show: false
    })
  },

  // 审批记录弹出框
  onApproveRecords(e) {
    var data_list = e
    var show_list = data_list.records;
    show_list[0].time = this.GMTToStr(show_list[0].time);
    show_list[0].action = show_list[0].action == "agree" ? "同意" : "不同意";
    for (var i in data_list.inspect_status) {
      const inspect_records = data_list.inspect_status[i].records;
      for (var j in inspect_records) {
        const inspect_record = inspect_records[j];
        var data_arr = {
          action: inspect_record.action == "agree" ? "同意" : "不同意",
          name: inspect_record.name,
          process: data_list.inspect_status[i].recycle_type + "->" + inspect_record.process,
          reason: inspect_record.reason,
          time: this.GMTToStr(inspect_record.time),
          user: inspect_record.user,
        };
        show_list.push(data_arr);
      }

    }
    let total = show_list.length
    let current_data = []
    current_data.push(show_list[0])
    this.setData({
      spjl_show: true,
      spjl_list: show_list,
      splj_total: total,
      spjl_list_1: current_data
    });
  },
  onspjlClose() {
    this.setData({
      spjl_show: false
    })
  },
  onspjlConfirm() {
    this.setData({
      spjl_show: false
    })
  },
  // 时间转换
  // GMTToStr(time) {
  //   let date = new Date(time);
  //   let Str = date.getFullYear() + '-' +
  //     (date.getMonth() + 1) + '-' +
  //     date.getDate() + ' '
  //   return Str
  // },


  /**
   * 生命周期函数--监听页面加载
   */
  // onLoad(options) {
  //   const scene = decodeURIComponent(options.scene)
  //   if (scene != "undefined") {
  //     if (this.data.previewImageClick == false) {
  //       this.checkID()
  //       this.getSupplyDatas(scene)
  //     }
  //   } else {
  //     const val = ""
  //     if (this.data.previewImageClick == false) {
  //       this.checkID()
  //       this.getSupplyDatas(val)
  //     }
  //   }
  // },
  // 点击记录步骤
  showStep(e) {
    if (this.data.steps[e.detail].file) {
      this.setData({
        now_steps: this.data.steps[e.detail],
        steps_img: true
      })

    }


  },
  preViewImg(e) {
    let lists = []
    lists.push('https://logisticsengineering.gree.com/package_integrated_api/photo_manage/fs_download?file_id=' + e.target.dataset.url)

    wx.previewImage({
      current: e.target.dataset.url,
      urls: lists,
    })
  },
  detailCancel() {
    this.setData({
      steps_img: false,
      now_steps: []
    })
  },
  onLoad(options) {
    this.checkID()
    let self = this
    const eventChannel = this.getOpenerEventChannel()
    // 监听acceptDataFromOpenerPage事件，获取上一页面通过eventChannel传送到当前页面的数据
    eventChannel.on('acceptDataFromOpenerPage', function (data) {
      console.log("传过来的数据", data)
      // self.onApproveRecords(data.task)
      self.getSupplyDatas(data.task)
      if (data.flag == "done") {
        self.setData({
          inspect_show: false,
        })
      }
      let arr = []
      arr.push(data.task)
      let steps_arr = []
      for (let i in data.task.records) {
        data.task.records[i].time = self.GMTToStr(data.task.records[i].time)
        data.task.records[i].action = data.task.records[i].action == "agree" ? "同意" : "不同意"
        let obj = {
          text: '【' + data.task.records[i].process + '】',
          desc: data.task.records[i].name + ' 在 ' + data.task.records[i].time + ' ' + ' ' + data.task.records[i].action + '办理，意见反馈：' + data.task.records[i].reason,
        }
        steps_arr.push(obj)
      }
      steps_arr[0] = {
        text: '【编制】',
        desc: data.task.records[0].name + ' 在 ' + data.task.records[0].time + ' 提交'
      }
      for (var i in data.task.inspect_status) {
        const inspect_records = data.task.inspect_status[i].records;
        for (var j in inspect_records) {
          const inspect_record = inspect_records[j];
          let result = inspect_record.reason.split("##");
          inspect_record.action = inspect_record.action == "agree" ? "同意" : "不同意"
          inspect_record.time = self.GMTToStr(inspect_record.time)
          let obj = {
            text: '【' + inspect_record.process + '】',
            desc: inspect_record.name + ' 在 ' + inspect_record.time + ' ' + ' ' + inspect_record.action + '办理，意见反馈：' + result.pop(),
            file: result[0]
          }
          steps_arr.push(obj)
        }

      }

      self.setData({
        task_row_data: data,
        task_id: data.task_id,
        business_content: data.business_content,
        creator_name: data.creator_name,
        lastProcessUser: data.lastProcessUser,
        lastProcessAction: data.lastProcessAction,
        data_arr: data.task,
        steps: steps_arr,
        active: steps_arr.length - 1,
        list: arr


      })


    })
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
  }
})